<template>
    <div class="container-fluid">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">

                    <div class="card-toolbar clearfix">
                        <form class="form-inline" onsubmit="return false;">
                            <div class="form-group">
                                <input class="form-control" type="text" id="example-if-email"
                                       name="example-if-email" placeholder="公司名称" v-model="keyword" autocomplete="off"/>
                            </div>
                            <div class="input-daterange input-group" style="width:30%;float: left;margin-right: 5px;">
                                <el-date-picker
                                        v-model="startTime"
                                        type="date"
                                        format="yyyy-MM-dd"
                                        @change="getStartTime"
                                        placeholder="选择日期">
                                </el-date-picker>
                                <span class="input-group-addon"><i class="mdi mdi-chevron-right"></i></span>
                                <el-date-picker
                                        v-model="endTime"
                                        type="date"
                                        @change="getEndTime"
                                        format="yyyy-MM-dd"
                                        placeholder="选择日期">
                                </el-date-picker>
                            </div>
                            <div class="form-group">
                                <button class="btn btn-success" type="submit" v-on:click="searchClick()">筛选</button>
                            </div>
                        </form>
                    </div>
                    <div class="card-body" v-loading="loading">
                        <div class="toolbar-btn-action">
                            <a class="btn btn-primary m-r-5" href="javascript:void(0)"
                               @click="openDialogFormVisible"><i class="mdi mdi-plus"></i> 新增</a>
                        </div>


                        <el-dialog title="创建公司" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
                            <el-form :model="form">
                                <el-form-item label="公司简称" :label-width="formLabelWidth">
                                    <el-input v-model="form.name" autocomplete="off" style="width: 80%"></el-input>
                                </el-form-item>

                                <el-form-item label="公司别称" :label-width="formLabelWidth">
                                    <el-tag
                                            :key="tag"
                                            v-for="tag in alternativeName"
                                            closable
                                            :disable-transitions="false"
                                            @close="handleClose(tag)">
                                        {{tag}}
                                    </el-tag>
                                    <el-input
                                            class="input-new-tag"
                                            v-if="inputVisible"
                                            v-model="inputValue"
                                            ref="saveTagInput"
                                            @keyup.enter.native="handleInputConfirm"
                                            @blur="handleInputConfirm"
                                            style="width: 80%;"
                                    >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加公司别称
                                    </el-button>
                                </el-form-item>
                                <!--<el-form-item label="关联分类" :label-width="formLabelWidth">
                                    <el-autocomplete
                                            v-model="form.categoryName"
                                            :fetch-suggestions="querySearchAsync"
                                            placeholder="请输入内容"
                                            @select="handleSelect"
                                            style="width: 100%"
                                    ></el-autocomplete>
                                    <el-tag
                                            :key="tag.id"
                                            v-for="tag in categoryTags"
                                            closable
                                            :disable-transitions="false"
                                            @close="handleIndustryClose(tag)">
                                        {{tag.value}}
                                    </el-tag>
                                </el-form-item>-->
                            </el-form>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogFormVisible = false">取 消</el-button>
                                <el-button type="primary" @click="submitCompany">确 定</el-button>
                            </div>
                        </el-dialog>



                        <el-dialog title="公司设置" :visible.sync="dialogEditFormVisible" :close-on-click-modal="false">
                            <el-form :model="form">
                                <el-form-item label="公司简称" :label-width="formLabelWidth">
                                    <input class="form-control" type="text" placeholder="任务标题" v-model="form.editName">
                                </el-form-item>

                                <el-form-item label="公司别称" :label-width="formLabelWidth">
                                    <el-tag
                                            :key="tag"
                                            v-for="tag in form.editAlternativeName"
                                            closable
                                            :disable-transitions="false"
                                            @close="handleEditClose(tag)">
                                        {{tag}}
                                    </el-tag>
                                    <el-input
                                            class="input-new-tag"
                                            v-if="inputVisible"
                                            v-model="inputValue"
                                            ref="saveTagInput"
                                            @keyup.enter.native="handleEditInputConfirm"
                                            @blur="handleInputConfirm"
                                            style="width: 80%;"
                                    >
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加公司别称
                                    </el-button>
                                </el-form-item>
                                <!--<el-form-item label="关联分类" :label-width="formLabelWidth">
                                    <el-autocomplete
                                            v-model="form.editIndustryName"
                                            :fetch-suggestions="querySearchAsync"
                                            placeholder="请输入内容"
                                            @select="handleEditSelect"
                                            style="width: 100%"
                                    ></el-autocomplete>
                                    <el-tag
                                            :key="tag.id"
                                            v-for="tag in editIndustryTags"
                                            closable
                                            :disable-transitions="false"
                                            @close="handleEditIndustryClose(tag)">
                                        {{tag.value}}
                                    </el-tag>
                                </el-form-item>-->
                            </el-form>
                            <div slot="footer" class="dialog-footer">
                                <el-button @click="dialogEditFormVisible = false">取 消</el-button>
                                <el-button type="primary" @click="updateCompany">确 定</el-button>
                            </div>
                        </el-dialog>

                        <div class="table-responsive" style="width: 100%;margin-top: 20px;">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                                    @sort-change='sortChange'
                                    :default-sort="{prop: '_id', order: 'descending'}"
                            >
                                <el-table-column
                                        label="ID"
                                        type="index"
                                        :index="indexMethod"
                                        align="center"
                                        width="50">
                                </el-table-column>
                                <el-table-column
                                        prop="name"
                                        label="公司名称"
                                        align="center"
                                        width="80">
                                    <template slot-scope="scope">
                                        <a @click="openEdit(scope.row._id)" style="cursor:pointer;">{{scope.row.name}}</a>
                                    </template>
                                </el-table-column>
                                <!--<el-table-column
                                        prop="categoryNames"
                                        :formatter="formatIndustry"
                                        align="center"
                                        label="关联分类"
                                        width="180">
                                </el-table-column>-->
                                <el-table-column
                                        prop="userName"
                                        label="创建用户"
                                        align="center"
                                        width="120">
                                </el-table-column>
                                <el-table-column
                                        prop="alternativeNameStr"
                                        :formatter="formatAlternative"
                                        label="别称"
                                        align="center"
                                        width="120">
                                </el-table-column>
                                <el-table-column
                                        prop="focusNum"
                                        label="关注用户"
                                        sortable
                                        align="center"
                                        width="100">
                                </el-table-column>
                                <el-table-column
                                        prop="created_at"
                                        label="创建时间"
                                        sortable
                                        align="center"
                                        width="180">
                                </el-table-column>
                                <el-table-column
                                        label="操作">
                                    <template slot-scope="scope">
                                        <el-button size="mini"
                                                @click="handleEdit(scope.row)" v-if="scope.row.status">设置</el-button>
                                        <el-button
                                                size="mini"
                                                type="danger"
                                                @click="handleDelete(scope.row._id)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>

                            <nav style="margin-top: 20px">
                                <el-pagination
                                        layout="total, sizes, prev, pager, next"
                                        :total="total"
                                        :hide-on-single-page="pageActive"
                                        @size-change="handleSizeChange"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        :page-sizes="[10, 20, 30, 40]"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>

    import common from '../../api/public.js';
    export default {
        name: "CompanyComponent",
        data() {
            return {
                startTime: '',
                endTime: '',
                keyword: '',
                pageActive: false,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: 1,
                name: '',
                order:'desc',
                orderField:'_id',
                form: {
                    name: "",
                    //categoryName:'',
                    editName:"",
                    editIndustryName:'',
                    editAlternativeName:[],
                },
                formLabelWidth: '120px',
                dialogTableVisible: false,
                dialogFormVisible: false,
                dialogEditFormVisible:false,
                inputVisible: false,
                inputValue: '',
                alternativeName: [],
                //categoryTags: [],
                //categoryIds:[],
                restaurants: [],
                state: '',
                timeout:  3000,
                id:0,
                //修改部分
                //editIndustryTags:[],
                //editIndustryIds:[]

            }
        },
        methods: {
            ...common,
            searchClick:function(){
                this.currentPage = 1;
                this.search();
            },
            search: function () {
                let self = this;
                let uri = 'company/post-list';
                self.loading = true;

                let postData = {
                    startTime: self.startTime, endTime: self.endTime,
                    keyword: self.keyword,
                    page: self.currentPage,
                    order:self.order,
                    orderField:self.orderField,
                    verifyStatus:1,
                    limit:self.pageSize
                };

                axios.post(uri,postData).then(function (result) {
                    self.total = result.companies.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.companies.data;
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            handleSizeChange: function (pageSize) {
                this.pageSize = pageSize;
                this.search();
            },
            getEndTime: function (date) {
                this.endTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            },
            getStartTime(date) {
                this.startTime = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
            },
            openDialogFormVisible() {
                this.dialogFormVisible = true;
                this.alternativeName = [];
                //this.categoryTags = [];
                //this.form.categoryName = '';
                this.form.name = '';
                this.id = 0;
                //this.categoryIds = [];
            },
            //下面是标签部分
            handleClose(tag) {
                this.alternativeName.splice(this.alternativeName.indexOf(tag), 1);
            },
            showInput() {
                this.inputVisible = true;
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                });
            },
            handleInputConfirm() {
                let inputValue = this.inputValue;

                if (inputValue && this.alternativeName.indexOf(inputValue) == -1) {
                    this.alternativeName.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            handleEditInputConfirm() {
                let inputValue = this.inputValue;

                if (inputValue && this.form.editAlternativeName.indexOf(inputValue) == -1) {
                    this.form.editAlternativeName.push(inputValue);
                }
                this.inputVisible = false;
                this.inputValue = '';
            },
            handleEditClose(tag) {
                this.form.editAlternativeName.splice(this.form.editAlternativeName.indexOf(tag), 1);
            },
            //查询分类
            async queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            async querySearchAsync(queryString, cb) {
                await this.queryIndustry(queryString);
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleSelect(item) {
                this.form.categoryName = '';
                if (item && this.categoryIds.indexOf(item.id) == -1) {
                    this.categoryTags.push(item);
                    this.categoryIds.push(item.id);
                }
            },
            handleIndustryClose(tag){
                this.categoryTags.splice(this.categoryTags.indexOf(tag), 1);
                this.categoryIds.push(tag.id);
            },
            submitCompany() {
                let self = this;
                self.loading = true;
                let uri = "company/store";
                let postData = {
                    name: self.form.name, alternativeName: self.alternativeName,
                    categoryIds: self.categoryIds};
                self.dialogFormVisible = false;

                axios.post(uri, postData).then(function (result) {
                    self.loading = false;
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            indexMethod:function (index) {
                return index +1;
            },
            formatIndustry:function (row, column) {
                return this.filterLength(row.categoryStr);
            },
            formatAlternative: function (row, column) {
                //return row.alternativeNameStr;
                return this.filterLength(row.alternativeNameStr,6);
            },
            filterLength: function (str,length = 9) {
                if (str.length >= length) {
                    return str.substring(0, length) + '...';
                }
                return str;
            },
            handleDelete:function (id) {
                let self = this;
                self.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.deleteRequire(id)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            deleteRequire: function (id) {
                let self = this;
                let uri = "company/" + id;
                axios.delete(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleEdit:function (row) {
                this.dialogEditFormVisible = true;
                this.form.editIndustryName = '';
                this.form.editAlternativeName = '';
                //this.editIndustryIds = [];


                this.form.editAlternativeName = row.alternativeName;
                /*let categoryNames = row.categoryNames;
                categoryNames.forEach((item) => {
                    this.editIndustryIds.push(item.id)
                });
                this.editIndustryTags = row.categoryNames;*/
                //this.form.categoryName = '';
                this.form.editName = row.name;
                this.id = row._id;
            },
            handleEditIndustryClose(tag){
                this.editIndustryTags.splice(this.editIndustryTags.indexOf(tag), 1);
                this.editIndustryIds.splice(this.editIndustryIds.indexOf(tag.id), 1);
            },
            handleEditSelect(item) {
                this.form.editIndustryName = '';
                if (item && this.editIndustryIds.indexOf(item.id) == -1) {
                    this.editIndustryTags.push(item);
                    this.editIndustryIds.push(item.id);
                }
            },
            updateCompany() {
                let self = this;
                self.loading = true;
                let uri = "company/update/"+self.id;
                let postData = {
                    alternativeName: self.form.editAlternativeName,
                    categoryIds: self.editIndustryIds,name:self.form.editName};
                self.dialogEditFormVisible = false;
                axios.put(uri,postData).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            sortChange(item){
                let order = "asc";
                this.orderField = item.prop;
                if (item.order === 'descending'){
                    order = "desc";
                }
                this.order = order;
                this.search();
            },
            openEdit(id) {
                this.openUri('company/article/' + id);
            }
        },
        created: function () {
            this.search();
        },
        mounted() {
            this.queryIndustry();
        }
    }
</script>

<style scoped>
    /*.el-date-editor.el-input, .el-date-editor.el-input__inner {
                width: 130px;
            }*/
    .el-input--suffix .el-input__inner {
        padding-right: 0;
    }

    .card-body .el-input__icon {
        /*height: 100%;
        width: 25px;*/
        width: 0;
        text-align: center;
        -webkit-transition: all .3s;
        transition: all .3s;
        line-height: 40px;
    }
</style>
